package com.bizhibihui.ordermeal.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bizhibihui.ordermeal.entity.BizFood;
import com.bizhibihui.ordermeal.mapper.BizFoodMapper;
import com.bizhibihui.ordermeal.service.BizFoodService;
import com.bizhibihui.ordermeal.util.CoreConst;
import com.bizhibihui.ordermeal.util.Pagination;
import com.bizhibihui.ordermeal.vo.FoodConditionVo;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 */
@Service
@AllArgsConstructor
public class BizFoodServiceImpl extends ServiceImpl<BizFoodMapper, BizFood> implements BizFoodService {

    private BizFoodMapper bizFoodMapper;

    @Override
    public List<BizFood> findByCondition(IPage<BizFood> page, FoodConditionVo vo) {
        List<BizFood> list = bizFoodMapper.findByCondition(page, vo);
        if (CollectionUtils.isNotEmpty(list)) {
            List<Integer> ids = new ArrayList<>();
            for (BizFood bizArticle : list) {
                ids.add(bizArticle.getId());
            }
            List<BizFood> listTag = bizFoodMapper.listTagsByFoodId(ids);
            // listTag, 重新组装数据为{id: Article}
            Map<Integer, BizFood> tagMap = new LinkedHashMap<>(listTag.size());
            for (BizFood bizArticle : listTag) {
                tagMap.put(bizArticle.getId(), bizArticle);
            }

            for (BizFood bizArticle : list) {
                BizFood tagArticle = tagMap.get(bizArticle.getId());
                if (Objects.nonNull(tagArticle)) {
                    bizArticle.setTags(tagArticle.getTags());
                }
            }
        }
        return list;
    }


    @Override
    public List<BizFood> recommendedList(int pageSize) {
        FoodConditionVo vo = new FoodConditionVo();
        vo.setRecommended(true);
        vo.setStatus(CoreConst.STATUS_VALID);
        vo.setPageSize(pageSize);
        IPage<BizFood> page = new Pagination<>(vo.getPageNumber(), vo.getPageSize());
        return this.findByCondition(page, vo);
    }




    @Override
    public BizFood selectById(Integer id) {
        return bizFoodMapper.getById(id);
    }

    @Override
    public BizFood insertFood(BizFood bizFood) {
        Date date = new Date();
        bizFood.setCreateTime(date);
        bizFood.setUpdateTime(date);
        bizFoodMapper.insert(bizFood);
        return bizFood;
    }

    @Override
    public int deleteBatch(Integer[] ids) {
        return bizFoodMapper.deleteBatch(ids);
    }

    @Override
    public List<BizFood> selectByCategoryId(Integer categoryId) {
        return bizFoodMapper.selectList(Wrappers.<BizFood>lambdaQuery().eq(BizFood::getCategoryId, categoryId));
    }
}
